package xyz.liuz.edb.heart.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;
import org.json.JSONObject;
import xyz.liuz.edb.heart.protocol.CoorMessageProtocol;

public class HeartClientHandler extends SimpleChannelInboundHandler<CoorMessageProtocol> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, CoorMessageProtocol msg) throws Exception {
        int messageType = msg.getMessageType();
        String msgString = new String(msg.getMessage(), CharsetUtil.UTF_8);
        if(messageType == 1){
            System.out.println("收到服务端（" + ctx.channel().remoteAddress() + "）心跳信息:" + msgString);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("连接服务端（" + ctx.channel().remoteAddress() + "）成功！");
        //连接成功,发送心跳
        CoorMessageProtocol heartMsg = new CoorMessageProtocol();
        heartMsg.setMessageType(1);
        //心跳信息为节点id、节点IP
        JSONObject msgJson = new JSONObject();
        msgJson.put("nodeId", "agent001");
        msgJson.put("agentHost", "127.0.0.1");
        heartMsg.setMessageLength(msgJson.toString().getBytes(CharsetUtil.UTF_8).length);
        heartMsg.setMessage(msgJson.toString().getBytes(CharsetUtil.UTF_8));
        ctx.channel().writeAndFlush(heartMsg);
        System.out.println("心跳发送成功!("+msgJson.toString()+"）");

//        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("与服务端（" + ctx.channel().remoteAddress() + "）断开！");
        HeartClinet.getInstance().start();

        super.channelInactive(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        System.out.println("空闲");
        if (evt instanceof IdleStateEvent){
            IdleStateEvent event = (IdleStateEvent) evt;
            System.out.println("空闲"+event.state());
            if (event.state() == IdleState.WRITER_IDLE){
                System.out.println("写空闲:"+ctx.channel().remoteAddress() );
                //发送心跳包
                CoorMessageProtocol heartMsg = new CoorMessageProtocol();
                heartMsg.setMessageType(1);
                //心跳信息为节点id、节点IP
                JSONObject msgJson = new JSONObject();
                msgJson.put("nodeId", "agent002");
                msgJson.put("agentHost", "127.0.0.1");
                heartMsg.setMessageLength(msgJson.toString().getBytes(CharsetUtil.UTF_8).length);
                heartMsg.setMessage(msgJson.toString().getBytes(CharsetUtil.UTF_8));
                ctx.channel().writeAndFlush(heartMsg);
                System.out.println("心跳发送成功!("+msgJson.toString()+"）");
            }

        }


        super.userEventTriggered(ctx, evt);
    }
}
